<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
import AddUserModal from './components/add-user-modal/index.vue';
import SetNicknameModal from './components/set-nickname-modal/index.vue';
import SetPasswordModal from './components/set-password-modal/index.vue';
import IntelModal from './components/intel-modal/index.vue';
import {
  getUserPage,
  changeBalance,
  addUser
} from "@/api/admin";
import { userUpdateBase } from "@/api/user";
import { ElMessage } from 'element-plus';
import { UserQuery, UserPageVO, } from "@/api/admin/types";
import { formatTimestamp, limitToTwoDecimalPlaces } from '@/utils/index'

const queryFormRef = ref(ElForm); // 查询表单
const keyModal = ref(0); // 用于刷新组件
const userInfo = ref<any>({}); // 用户信息
const visibleModal = ref(false);
const visibleNicknameModal = ref(false);
const visiblePasswordModal = ref(false);
const visibleIntelModal = ref(false);
const loading = ref(false);
const total = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
  title: '改变余额'
});

const queryParams = reactive<UserQuery>({
  page: 1,
  ps: 10,
});

const userList = ref<UserPageVO[]>();

// 获取表单
const menuFormRef = ref(ElForm);

// 表单提交数据
const formData = reactive<any>({
  uid: '',
  io: 1,
  amount: '',
  desc: '',
});

// 表单验证
const rules = reactive({
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
  desc: [{ required: true, message: "请输入变动原因说明文字", trigger: "blur" }]
});


/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getUserPage(queryParams)
    .then(({ data }) => {
      userList.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  handleQuery();
}

// 打开弹窗
const openDialog = (id?: number) => {
  formData.uid = id;
  dialog.visible = true;
}

// 确认提交
const submitForm = () => {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      changeBalance(formData).then((res: any) => {
        ElMessage.success(res.msg);
        closeDialog();
        resetQuery();
      })
    }
  })
}

// 新增用户
const handleSubmit = async (event: any) => {
  const res: any = await addUser({
    tel: `${event.area_code}${event.tel}`,
    nickname: event.nickname,
    login_secret: event.login_secret,
    pid: 0
  });

  visibleModal.value = false;

  if (res.code === 200) {
    ElMessage.success('创建成功!');
  }
}

// 禁用用户或启用
const handDisableEnable = (id: number, login_status: number) => {
  userUpdateBase({
    id: id,
    field_name: "login_status",
    value: login_status
  }).then((res: any) => {
    if (res.code === 200) {
      ElMessage.success('操作成功!');
      handleQuery();
    }
  })
};

// 修改用户昵称
const handSetNickname = (params: any, type: string) => {
  keyModal.value = new Date().getTime();
  userInfo.value = params;
  if (type === "password") {
    visiblePasswordModal.value = true;
  } else if (type === 'nickname') {
    visibleNicknameModal.value = true;
  } else if (type === 'intel') {
    visibleIntelModal.value = true;
  }
};

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.uid = undefined;
  formData.amount = '';
  formData.io = 1;
  formData.desc = '';
}

// 限制输入小数
const amountInput = (event: any) => {
  formData.amount = limitToTwoDecimalPlaces(event)
}

onMounted(() => {
  handleQuery(); // 初始化用户列表数据
});
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :lg="24" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="手机号" prop="s_tel">
              <el-input v-model="queryParams.s_tel" placeholder="输入手机号" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="昵称" prop="s_nickname">
              <el-input v-model="queryParams.s_nickname" placeholder="输入昵称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="用户id" prop="id">
              <el-input v-model="queryParams.id" placeholder="输入昵称" clearable style="width: 200px"
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
              <el-button @click="resetQuery">
                <i-ep-refresh />
                重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button v-hasPerm="['user:add']" type="primary" @click="visibleModal = true">添加用户</el-button>
                <!-- <el-button type="success"><i-ep-plus />设置管理</el-button> -->
              </div>
            </div>
          </template>
          <el-table v-hasPerm="['user:pageList']" v-loading="loading" border :data="userList">
            <el-table-column label="用户id" align="center" prop="id" width="100" />
            <el-table-column label="注册手机号" align="center" prop="tel" width="160" />
            <el-table-column label="昵称" align="center" prop="nickname" width="120" />
            <el-table-column label="余额" align="center" prop="balance" width="160" />
            <el-table-column label="冻结余额" align="center" prop="frozen_balance" width="160" />
            <el-table-column label="邀请码" align="center" prop="invite_code" width="120" />
            <el-table-column label="状态" align="center" width="80">
              <template #default="scope">
                <span v-if="scope.row.login_status === 1" style="color: #67c23a;">正常</span>
                <span v-else-if="scope.row.login_status === 2" style="color: #f56c6c;">禁用</span>
              </template>
            </el-table-column>
            <el-table-column label="注册ip" align="center" prop="reg_ip" width="150" />
            <el-table-column label="注册时间" align="center" prop="reg_at" width="180">
              <template #default="scope">
                {{ formatTimestamp(scope.row.reg_at * 1000) }}
              </template>
            </el-table-column>
            <el-table-column label="最后登录时间" align="center" prop="reg_at" width="180">
              <template #default="scope">
                <span v-if="scope.row.last_login_at == 0"></span>
                <span v-else>{{ formatTimestamp(scope.row.last_login_at * 1000) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="下单时间" align="center" prop="created_at" width="180">
              <template #default="scope">
                {{ formatTimestamp(scope.row.created_at * 1000) }}
              </template>
            </el-table-column>
            <el-table-column v-hasPerm="['changeBalance', 'user:updateBase', 'user:detail']" label="操作" fixed="right"
              align="center" width="420">
              <template #default="scope">
                <el-button v-hasPerm="['changeBalance']" @click="openDialog(scope.row.id)" type="primary"
                  size="small">改变余额</el-button>
                <el-button v-hasPerm="['user:updateBase']" v-if="scope.row.login_status === 1"
                  @click="handDisableEnable(scope.row.id, 2)" type="primary" size="small">禁用</el-button>
                <el-button v-hasPerm="['user:updateBase']" v-else-if="scope.row.login_status === 2"
                  @click="handDisableEnable(scope.row.id, 1)" type="primary" size="small">启动</el-button>
                <el-button v-hasPerm="['user:updateBase']" @click="handSetNickname(scope.row, 'nickname')"
                  type="primary" size="small">修改昵称</el-button>
                <el-button v-hasPerm="['user:updateBase']" @click="handSetNickname(scope.row, 'password')"
                  type="primary" size="small">修改密码</el-button>
                <el-button v-hasPerm="['user:detail']" @click="handSetNickname(scope.row, 'intel')" type="primary"
                  size="small">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-hasPerm="['user:pageList']" v-if="total > 0" v-model:total="total"
            v-model:page="queryParams.page" v-model:limit="queryParams.ps" @pagination="handleQuery" />
        </el-card>
      </el-col>
    </el-row>

    <add-user-modal :visible="visibleModal" @close="visibleModal = false" @submit="handleSubmit" />
    <set-nickname-modal :key="keyModal" :visible="visibleNicknameModal" :userInfo="userInfo"
      @close="visibleNicknameModal = false" @submit="handleQuery" />
    <!--  -->
    <set-password-modal :key="keyModal" :visible="visiblePasswordModal" :user-info="userInfo"
      @close="visiblePasswordModal = false" @submit="handleQuery" />
    <intel-modal :key="keyModal" :visible="visibleIntelModal" :user-info="userInfo"
      @close="visibleIntelModal = false" />


    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="500px"
      @close="closeDialog">
      <el-form ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="充值类型" prop="io">
          <el-radio-group v-model="formData.io">
            <el-radio :value="1">加钱</el-radio>
            <el-radio :value="2">减钱</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model.lazy="formData.amount" @input="amountInput" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="变动说明" prop="desc">
          <el-input v-model="formData.desc" placeholder="请输入变动说明" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
